<?php
/**
 * 加密解密工具类
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/5/20
 * Time: 20:46
 */

namespace app\service;

class Cipher
{
    public static $salt = "gnota";

    /**
     * 加密器
     * @param $string
     * @param $salt
     * @return string
     */
    public static function encrypt($string)
    {
        $char = $str = '';

        $salt = md5(self::$salt);
        $x = 0;
        $len = strlen($string);
        $l = strlen($salt);

        for ($i = 0; $i < $len; $i++) {
            if ($x == $l) {
                $x = 0;
            }
            $char .= $salt{$x};
            $x++;
        }
        for ($i = 0; $i < $len; $i++) {
            $str .= chr(ord($string{$i}) + (ord($char{$i})) % 256);
        }
        return base64_encode($str);
    }

    /**
     * 解密器
     * @param $string
     * @return string
     */
    public static function decrypt($string)
    {
        $char = $str = '';

        $salt = md5(self::$salt);
        $x = 0;
        $string = base64_decode($string);
        $len = strlen($string);
        $l = strlen($salt);

        for ($i = 0; $i < $len; $i++) {
            if ($x == $l) {
                $x = 0;
            }
            $char .= substr($salt, $x, 1);
            $x++;
        }
        for ($i = 0; $i < $len; $i++) {
            if (ord(substr($string, $i, 1)) < ord(substr($char, $i, 1))) {
                $str .= chr((ord(substr($string, $i, 1)) + 256) - ord(substr($char, $i, 1)));
            } else {
                $str .= chr(ord(substr($string, $i, 1)) - ord(substr($char, $i, 1)));
            }
        }
        return $str;
    }
}